package com.zj.album.graphy;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.zj.album.graphy.module.PhotoFileInfo;
import com.zj.album.utils.DebugUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaojie on 2017/10/20.
 * 异步从本地文件夹获取Android的所有图片，
 * this.getInstance().getImageData()
 */

public final class GraphUtils {

    private WeakReference<Activity> activity;
    private PhotoGraphHandler handler;
    private GetImageTask mTask;

    public void getImgData(Activity act, GetImgData dataListener) {
        activity = new WeakReference<>(act);
        handler = new PhotoGraphHandler(this, dataListener);
        mTask = new GetImageTask(handler);
        mTask.execute(activity.get());
    }

    public static class GetImageTask extends AsyncTask<Activity, Integer, List<PhotoFileInfo>> {

        private HashMap<String, List<String>> mGruopMap = new HashMap<>();
        private WeakReference<PhotoGraphHandler> wek_handler;

        public GetImageTask(PhotoGraphHandler wek) {
            this.wek_handler = new WeakReference(wek);
        }

        @Override
        protected List<PhotoFileInfo> doInBackground(Activity... activities) {
            try {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = activities[0].getContentResolver();
                //只查询jpeg的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/jpg"}, MediaStore.Images.Media.DATE_MODIFIED);
                if (mCursor == null || isCancelled()) {
                    return null;
                }

                while (mCursor.moveToNext()) {
                    if (isCancelled()) return null;
                    //获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    boolean isContainInFilter = false;
                    for (String filter : Manifest.ignore) {
                        if (!TextUtils.isEmpty(filter) && path.indexOf(filter) > 0) {
                            isContainInFilter = true;
                            break;
                        }
                    }
                    if (!isContainInFilter) {
                        //获取该图片的父路径名
                        String parentName = new File(path).getParentFile().getName();
                        //根据父路径名将图片放入到mGruopMap中
                        if (!mGruopMap.containsKey(parentName)) {
                            List<String> chileList = new ArrayList<>();
                            chileList.add(path);
                            mGruopMap.put(parentName, chileList);
                        } else {
                            mGruopMap.get(parentName).add(path);
                        }
                    }
                }
                mCursor.close();
                return subGroupOfImage(mGruopMap);
            } catch (Exception e) {
                DebugUtils.e("GraphUtils.GetImageTask   erro  :" + e);
                if (wek_handler != null && wek_handler.get() != null) {
                    wek_handler.get().sendEmptyMessage(-1);
                    wek_handler.clear();
                }
                return null;
            } finally {
                mGruopMap.clear();
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            if (wek_handler != null && wek_handler.get() != null) {
                wek_handler.get().sendEmptyMessage(-1);
                wek_handler.clear();
            }
            DebugUtils.e("getImageTask is canceled");
        }

        @Override
        protected void onPostExecute(List<PhotoFileInfo> photoFileInfos) {
            if (isCancelled() || photoFileInfos == null) return;
            Message msg = Message.obtain();
            msg.what = 100;
            msg.obj = photoFileInfos;
            if (wek_handler != null && wek_handler.get() != null) {
                wek_handler.get().sendMessage(msg);
                wek_handler.clear();
            }
        }

        /**
         * 组装分组界面GridView的数据源，因扫描手机的时候将图片信息放在HashMap中
         * 所以需要遍历HashMap将数据组装成List
         */
        private List<PhotoFileInfo> subGroupOfImage(HashMap<String, List<String>> mGruopMap) {
            if (mGruopMap.size() == 0 || isCancelled()) {
                return null;
            }
            List<PhotoFileInfo> list = new ArrayList<>();
            Iterator<Map.Entry<String, List<String>>> it = mGruopMap.entrySet().iterator();
            while (it.hasNext() && !isCancelled()) {
                if (isCancelled()) return null;
                Map.Entry<String, List<String>> entry = it.next();
                PhotoFileInfo info = new PhotoFileInfo();
                String key = entry.getKey();
                List<String> value = entry.getValue();
                info.parentPath = key;
                info.imageCounts = value.size();
                info.topImgUri = "file://" + value.get(0);//获取该组的第一张图片
                info.imgUris = value;
                list.add(info);
            }
            return isCancelled() ? null : list;
        }
    }

    public static class PhotoGraphHandler extends Handler {

        private WeakReference<GetImgData> getImgData;
        private WeakReference<GraphUtils> utils;

        public PhotoGraphHandler(GraphUtils graphUtils, GetImgData getImgData) {
            this.getImgData = new WeakReference(getImgData);
            this.utils = new WeakReference(graphUtils);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 100) {
                List<PhotoFileInfo> infos = (List<PhotoFileInfo>) msg.obj;
                if (getImgData != null && getImgData.get() != null)
                    if (infos != null) getImgData.get().onGetParent(infos);
                    else getImgData.get().onFail();
            } else if (msg.what == -1) {
                if (getImgData != null && getImgData.get() != null) getImgData.get().onFail();
            }
        }

        public void clear() {
            getImgData.clear();
            getImgData = null;
            utils.clear();
            utils = null;
        }
    }

    public interface GetImgData {
        void onGetParent(List<PhotoFileInfo> infos);

        void onFail();
    }

    public void onDestory() {
        if (mTask != null) {
            mTask.cancel(false);
            mTask = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler.clear();
            handler = null;
        }
        if (activity != null) {
            activity.clear();
            activity = null;
        }

    }
}
